package cn.itrip.auth.controller;

import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * Token控制器
 *
 * @author hduser
 */
@Api("toKen模块")
@Controller
@RequestMapping(value = "/api")
public class TokenController {
    @Resource
    private TokenService tokenService;

    /**
     * 验证token
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "验证token", notes = "提供客户端验证token操作")
    @RequestMapping(value = "/validateToken", method = RequestMethod.GET, produces = "application/json", headers = "token")
    @ResponseBody
    public Dto validateToken(HttpServletRequest request) {
        try {
            boolean result = tokenService.validateToken(request.getHeader("user-agent"), request.getHeader("token"));
            if (result) {
                return DtoUtil.returnSuccess("token有效");
            } else {
                return DtoUtil.returnSuccess("token无效");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 置换token
     *
     * @param request
     * @return 新的token信息
     */
    @ApiOperation(value = "客户端置换token", httpMethod = "POST", protocols = "HTTP", produces = "application/json", response = Dto.class, notes = "提供客户端置换token操作，服务器需要获取客户端header中的token串")
    @ApiImplicitParam(paramType = "header", required = true, name = "token", value = "用户认证凭据", defaultValue = "token:PC-21ec64d6e9cae0917ea4b54bc36809d8-8-20170601100121-699dfc")
    @RequestMapping(value = "/retoken", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody Dto replaceToken(HttpServletRequest request) {
        String token;
        try {
            token = this.tokenService.reloadToken(request.getHeader("user-agent"), request.getHeader("token"));
            ItripTokenVO tokenVO = new ItripTokenVO(token, Calendar.getInstance().getTimeInMillis() + 2 * 60 * 60 * 1000, Calendar.getInstance().getTimeInMillis());
            return DtoUtil.returnDataSuccess(tokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getLocalizedMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }
}
